package com.xingfly.product.product;

import com.xingfly.product.sdk.representaion.ProductWithCategoryRepresentation;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;


/**
 * Created by SuperS on 2019/11/21.
 *
 * @author SuperS
 */
@Service
public class ProductRepresentationService {

    private final NamedParameterJdbcTemplate jdbcTemplate;

    public ProductRepresentationService(NamedParameterJdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    private static final String FIND_PRODUCT_WITH_CATEGORY_SQL = "select " +
            "product.id as productId,product.name as productName," +
            "category.id as categoryId," +
            "category.name as categoryName " +
            "from t_product product " +
            "left join t_category category on product.category_id = category.id " +
            "where product.id = :productId";

    public ProductWithCategoryRepresentation productWithCategory(String id) {
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("productId", id);
        return jdbcTemplate.queryForObject(FIND_PRODUCT_WITH_CATEGORY_SQL, parameters,
                (rs, rowNum) -> new ProductWithCategoryRepresentation(
                        rs.getString("productId"),
                        rs.getString("productName"),
                        rs.getString("categoryId"),
                        rs.getString("categoryName")));
    }
}
